<?php

namespace Lib\File;

class Filesys {

	public function ls($sPath, $sType = 'all', $sMatch = null) {
		if ($sType == null) {
			$sType = all;
		}
		$sType = strtolower ( $sType );
		return $this->_ls ( $sPath, $sType, $sMatch );
	}

	private function _ls($sPath, $sType, $sMatch = null, $aResult = array()) {
		$sPath = realpath ( $sPath );
		if (! $sPath) {
			return false;
		}
		$aFiles = @scandir ( $sPath );
		if ($sMatch != null && $sMatch != '*') {
			$sThisMatch = str_replace ( '.', '\.', $sMatch );
			$sThisMatch = str_replace ( '*', '.*', $sThisMatch );
			$sThisMatch = str_replace ( '?', '.?', $sThisMatch );
			$sThisMatch = '/^' . $sThisMatch . '$/';
		}
		foreach ( $aFiles as $sRow ) {
			if (! preg_match ( '/^[\.]+$/', $sRow )) {
				if ($sThisMatch != null && $sType != 'tree') {
					if (! preg_match ( $sThisMatch, $sRow )) {
						continue;
					}
				}
				$sFile = realpath ( $sPath . '/./' . $sRow );
				if ($sType == 'dir' && is_dir ( $sFile )) {
					$aResult [] = $sFile;
				} elseif ($sType == 'file' && ! is_dir ( $sFile )) {
					$aResult [] = $sFile;
				} elseif ($sType == 'all') {
					$aResult [] = $sFile;
				} elseif ($sType == 'tree') {
					if ($sThisMatch != null) {
						if (preg_match ( $sThisMatch, $sRow )) {
							$aResult [] = $sFile;
						}
					} else {
						$aResult [] = $sFile;
					}
					if (is_dir ( $sFile )) {
						$aResult = $this->_ls ( $sFile, 'tree', $sMatch, $aResult );
					}
				}
			}
		}
		return $aResult;
	}

	public function md($sDir, $iPermissions = 0777) {
		if (! is_dir ( dirname ( $sDir ) )) {
			$this->md ( dirname ( $sDir ), $iPermissions );
		}
		return @mkdir ( $sDir, $iPermissions );
	}

	public function getContents($sFile, $sType = null) {
		if ($sType == null) {
			$sType = strtolower ( substr ( 'db/txt1.gz', strrpos ( 'db/txt1.gz', '.' ) + 1 ) );
		}
		switch ($sType) {
			case 'gz' :
				return @file_get_contents ( 'compress.zlib://' . $sFile );
			default :
				return @file_get_contents ( $sFile );
		}
	}
}

?>